<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;



class Test extends Controller
{
    // public function feishuExport(){
    //     set_time_limit ( 0 );
    //     ini_set('memory_limit','2048M');

    //     $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load('C:/abcd.xlsx');
    //     $list=$spreadsheet->getsheet(0)->toArray();   //转换为数组格式
    //     array_shift($list);  //删除第一个数组(标题);

    //     $fields = json_decode('["Name","OwnerId","PreSalesOwner__c","Country_Region__c","Sub_Region__c","State__c","City__c","Number_of_Employees__c","BusinessPrimaryIndustry__c","BusinessSecondaryIndustry__c","BusinessTertiaryIndustry__c","Type","NamedAccountCategories__c","GlobalBusinessSites__c","OverseasEntityTypes__c","EnterpriseQualification__c","IsStateOwnedEnterprise__c","ListingStatus__c","FinancingActivities__c","BusinessRisk__c","AnnualProfit__c","QuarterlyProfit__c","AnnualRevenue__c","QuarterlyRevenue__c","PaidStatus__c","QuotaStatus__c","Close_Won_Opportunity__c","CountofOpportunity__c","ReleaseCountdown__c","LastActivityDate","ActiveARRCNY__c","ActiveARRUSD__c","UsageExceedLimitation__c","GroupAccount__c","IsGroupAccount__c","ChannelManager__c"]',true);

    //     // foreach ($fields as $k => $vo) {
    //     //     echo '`'.$vo.'` varchar(255) NULL COMMENT "",';
    //     //     echo '<Br />';
    //     // }
    //     // die;


    //     $api_url = 'https://activity.feishu.cn/api/salesforce/sf_sales_view/account/page_account';
    //     $cookie = 'lang=zh; passport_trace_id=7389943425808941059; locale=zh-CN; session=XN0YXJ0-167g07f7-4487-4c54-9a5c-2f600f73faa5-WVuZA; session_list=XN0YXJ0-167g07f7-4487-4c54-9a5c-2f600f73faa5-WVuZA_XN0YXJ0-c3cmca0a-0e86-4b50-9dbb-eaa6c5378fe1-WVuZA_XN0YXJ0-920s2c09-2aa1-4d49-8cf7-45de03eea8a1-WVuZA; sid=00D0o000001RVoQ!AQEAQKJE17n99ryKhWyMWF1V_hr9TQ3EwKZ_dULIx4UX56c1r8s4VuN8N3bXFkCBtBA108TGuNIBqumt2bKADInSLqwbMm0R';
    //     $headers = [
    //         'content-type:application/json',
    //         'origin:https://activity.feishu.cn',
    //         'cookie:'.$cookie
    //     ];
    //     $bodys = json_decode('{"objectApiName":"Account","fields":["Name","OwnerId","PreSalesOwner__c","Country_Region__c","Sub_Region__c","State__c","City__c","Number_of_Employees__c","BusinessPrimaryIndustry__c","BusinessSecondaryIndustry__c","BusinessTertiaryIndustry__c","Type","NamedAccountCategories__c","GlobalBusinessSites__c","OverseasEntityTypes__c","EnterpriseQualification__c","IsStateOwnedEnterprise__c","ListingStatus__c","FinancingActivities__c","BusinessRisk__c","AnnualProfit__c","QuarterlyProfit__c","AnnualRevenue__c","QuarterlyRevenue__c","PaidStatus__c","QuotaStatus__c","Close_Won_Opportunity__c","CountofOpportunity__c","ReleaseCountdown__c","LastActivityDate","ActiveARRCNY__c","ActiveARRUSD__c","UsageExceedLimitation__c","GroupAccount__c","IsGroupAccount__c","ChannelManager__c"],"referenceFields":[{"fieldApi":"TeamMemberRole","referenceObject":"AccountTeamMember"},{"fieldApi":"Latest_Total_DAU__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"Latest_Activated_Users__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"ApiCallCount__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"LatestPersonDAUWeekdayAvg__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"ASRExcessUserRatio__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"IsCertified__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"Total_Storage_Usage__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"Tenant_Created_Date__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"X30dayDAUGrowthRate__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"X30dayDAUGrowthValue__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"X60dayDAUGrowthRate__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"X60dayDAUGrowthValue__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"X90dayDAUGrowthRate__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"X90dayDAUGrowthValue__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"BaseAdvPermDashboardCnt__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"BaseEventConnectorCnt__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"BaseMaxChartTableCnt__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"BaseMaxLoopConfig__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"BaseMaxLoopInstanceCnt__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"BaseRecordFieldViewRuleFCnt__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"BaseViewRuleFCnt__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"BaseWebhookTriggerWorkflowCnt__c","referenceObject":"Digital_Asset__c"}],"keyword":"","filter":{"relation":"OR","subFilters":[{"relation":"AND","subFilters":[{"relation":"OR","subFilters":[{"relation":"AND","expressions":[{"left":"OwnerId","leftType":"reference","operator":"IN","right":["0050o00000XRXKiAAP"]}]}]}]}]},"limit":1000,"pageIndex":1,"sorter":[]}',true);

    //     $total = 1000000;
    //     $bodys['pageIndex'] = Db::name('test')->where('id',1)->value('content');
    //     $bodys['pageIndex'] = intval($bodys['pageIndex']);
    //     while (($bodys['pageIndex'] - 1) * $bodys['limit'] < $total) {
    //         $result = httpRequest($api_url,json_encode($bodys),'POST',$headers);
    //         $result = json_decode($result,true);
    //         dump($result);die;

    //         // dump(count($result['data']['records']));
    //         // unset($result['data']['records']);
    //         // dump($result);

    //         if ($result['code'] != '0' || empty($result['data']['records'])) {
    //             break;
    //         }


    //         $total = $result['data']['total'];

            

    //         $list = $result['data']['records'];
    //         $data = [];
    //         foreach ($list as $k => $vo) {
    //             $tmp = [];
    //             foreach ($fields as $field) {
    //                 $vals = $vo[$field];
    //                 if (is_array($vals)) {
    //                     $vals = implode(';',$vals);
    //                 }
    //                 $tmp[$field] = $vals;
    //             }
    //             $data[] = $tmp;
    //         }
    //         Db::name('feishu_data')->insertAll($data);

    //         $bodys['pageIndex'] ++;
    //         Db::name('test')->where('id',1)->update(['content'=>$bodys['pageIndex']]);

    //         sleep(2);
    //     }
    //     die;

    //     exportCsv(date('YmdHis'),$fields,$data);
    // }

    public function feishuExport(){
        set_time_limit ( 0 );
        ini_set('memory_limit','2048M');

        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load('C:/abcd.xlsx');
        $excels=$spreadsheet->getsheet(0)->toArray();   //转换为数组格式
        array_shift($excels);  //删除第一个数组(标题);

        $fields = json_decode('["Name","OwnerId","PreSalesOwner__c","Country_Region__c","Sub_Region__c","State__c","City__c","Number_of_Employees__c","BusinessPrimaryIndustry__c","BusinessSecondaryIndustry__c","BusinessTertiaryIndustry__c","Type","NamedAccountCategories__c","GlobalBusinessSites__c","OverseasEntityTypes__c","EnterpriseQualification__c","IsStateOwnedEnterprise__c","ListingStatus__c","FinancingActivities__c","BusinessRisk__c","AnnualProfit__c","QuarterlyProfit__c","AnnualRevenue__c","QuarterlyRevenue__c","PaidStatus__c","QuotaStatus__c","Close_Won_Opportunity__c","CountofOpportunity__c","ReleaseCountdown__c","LastActivityDate","ActiveARRCNY__c","ActiveARRUSD__c","UsageExceedLimitation__c","GroupAccount__c","IsGroupAccount__c","ChannelManager__c"]',true);

        // foreach ($fields as $k => $vo) {
        //     echo '`'.$vo.'` varchar(255) NULL COMMENT "",';
        //     echo '<Br />';
        // }
        // die;


        $api_url = 'https://activity.feishu.cn/api/salesforce/sf_sales_view/account/page_account';
        $cookie = 'lang=zh; passport_trace_id=7389943425808941059; locale=zh-CN; session=XN0YXJ0-167g07f7-4487-4c54-9a5c-2f600f73faa5-WVuZA; session_list=XN0YXJ0-167g07f7-4487-4c54-9a5c-2f600f73faa5-WVuZA_XN0YXJ0-c3cmca0a-0e86-4b50-9dbb-eaa6c5378fe1-WVuZA_XN0YXJ0-920s2c09-2aa1-4d49-8cf7-45de03eea8a1-WVuZA; sid=00D0o000001RVoQ!AQEAQKJE17n99ryKhWyMWF1V_hr9TQ3EwKZ_dULIx4UX56c1r8s4VuN8N3bXFkCBtBA108TGuNIBqumt2bKADInSLqwbMm0R';
        $headers = [
            'content-type:application/json',
            'origin:https://activity.feishu.cn',
            'cookie:'.$cookie
        ];
        $bodys = json_decode('{"objectApiName":"Account","fields":["Name","OwnerId","PreSalesOwner__c","State__c","City__c","Number_of_Employees__c","BusinessPrimaryIndustry__c","BusinessSecondaryIndustry__c","BusinessTertiaryIndustry__c","ReleaseCountdown__c","Country_Region__c","Sub_Region__c","Type","NamedAccountCategories__c","GlobalBusinessSites__c","OverseasEntityTypes__c","EnterpriseQualification__c","IsStateOwnedEnterprise__c","ListingStatus__c","FinancingActivities__c","BusinessRisk__c","AnnualProfit__c","QuarterlyProfit__c","AnnualRevenue__c","QuarterlyRevenue__c","PaidStatus__c","QuotaStatus__c","Close_Won_Opportunity__c","CountofOpportunity__c","LastActivityDate","ActiveARRCNY__c","ActiveARRUSD__c","UsageExceedLimitation__c","GroupAccount__c","IsGroupAccount__c","ChannelManager__c"],"referenceFields":[{"fieldApi":"TeamMemberRole","referenceObject":"AccountTeamMember"},{"fieldApi":"Latest_Total_DAU__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"Latest_Activated_Users__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"ApiCallCount__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"LatestPersonDAUWeekdayAvg__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"ASRExcessUserRatio__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"IsCertified__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"Total_Storage_Usage__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"Tenant_Created_Date__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"X30dayDAUGrowthRate__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"X30dayDAUGrowthValue__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"X60dayDAUGrowthRate__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"X60dayDAUGrowthValue__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"X90dayDAUGrowthRate__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"X90dayDAUGrowthValue__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"BaseAdvPermDashboardCnt__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"BaseEventConnectorCnt__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"BaseMaxChartTableCnt__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"BaseMaxLoopConfig__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"BaseMaxLoopInstanceCnt__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"BaseRecordFieldViewRuleFCnt__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"BaseViewRuleFCnt__c","referenceObject":"Digital_Asset__c"},{"fieldApi":"BaseWebhookTriggerWorkflowCnt__c","referenceObject":"Digital_Asset__c"}],"keyword":"广州仕邦人力资源有限","filter":{"relation":"OR","subFilters":[]},"limit":200,"pageIndex":1,"sorter":[]}',true);

        $total = Db::name('test')->where('id',1)->value('content');
        intval($total);

        foreach ($excels as $e_k => $e_v) {
            if ($e_k <= $total) {
                continue;
            }
            $bodys['keyword'] = $e_v[0];

            $result = httpRequest($api_url,json_encode($bodys),'POST',$headers);
            $result = json_decode($result,true);

            if ($result['code'] != '0' || empty($result['data']['records'])) {
                continue;
            }

            $list = $result['data']['records'];
            $data = [];
            foreach ($list as $k => $vo) {
                $tmp = ['my_name'=>$e_v[0]];
                foreach ($fields as $field) {
                    $vals = $vo[$field];
                    if (is_array($vals)) {
                        $vals = implode(';',$vals);
                    }
                    $tmp[$field] = $vals;
                }
                $data[] = $tmp;
            }
            Db::name('feishu_data')->insertAll($data);

            Db::name('test')->where('id',1)->update(['content'=>$e_k]);
        }
        
        echo 11;die;

    }
    
    public function update_customer(){
        $id = Db::name('test')->where('id',1)->value('content');
        $list = Db::name('customer')->field('id,name')->where('id','>',$id)->select();
        
        foreach ($list as $k => $vo) {
            $names = explode(' ',$vo['name']);
            $update_name = '';
            if (count($names) <= 1) {
                continue;
            }
            if ($names[0] == $names[1]) {
                $update_name = $names[0];
            }else{
                if (strlen($names[0]) > strlen($names[1])) {
                    $update_name = $names[0];
                }else{
                    $update_name = $names[1];
                }
            }
            if (!empty($update_name)) {
                Db::name('customer')->where('id',$vo['id'])->update(['name'=>$update_name]);    
            }
            
            Db::name('test')->where('id',1)->update(['content'=>$vo['id']]);
        }
    }

	public function qy_sale()
    {
    	$dsn_config = [
	        'type'=>'mysql',
	        'hostname'=> '127.0.0.1',
	        'database'=> 'delisystemdb',
	        'username'=> 'root',
	        'password'=> 'root',
	    ];
        $list = Db::connect($dsn_config)->table('cms_sale')->select();
        $save_datas = [];
        foreach ($list as $k => $vo) {
        	$save_datas[] = [
        		'id'=>$vo['id'],
        		'password'=>$vo['password'],
        		'truename'=>$vo['truename'],
        		'mobile'=>$vo['mobile'],
        		'ctime'=>$vo['ctime'],
        		'team_id'=>$vo['team_id'],
        		'email'=>$vo['email'],
        		'region'=>$vo['region'],
        		'seats_id'=>$vo['seats_id'],
        	];
        }

        $result = Db::name('sale')->insertAll($save_datas);
        dump($result);die;
    }

    public function qy_customer()
    {
    	set_time_limit ( 0 );

    	$dsn_config = [
	        'type'=>'mysql',
	        'hostname'=> '127.0.0.1',
	        'database'=> 'delisystemdb',
	        'username'=> 'root',
	        'password'=> 'root',
	    ];
        $list = Db::connect($dsn_config)->table('cms_customer')->order('id','asc')->select();
        $save_datas = [];
        foreach ($list as $k => $vo) {
        	$tmp = [
        		'id'=>$vo['id'],
        		'name'=>$vo['truename'],
        		'type'=>$vo['type'],
        		'sale_id'=>$vo['sale_id'],
        		'mobile'=>$vo['mobile'],
        		'ctime'=>$vo['ctime'],
        		'wechat'=>$vo['wechat'],
        		'website'=>$vo['website'],
        		'utime'=>$vo['utime'],
        		'remark'=>$vo['remark'],
        		'tags'=>$vo['tags'],
        		'trade'=>$vo['trade'],
        		'address'=>$vo['address'],
        		'province'=>$vo['province'],
        		'city'=>$vo['city'],
        		'area'=>$vo['area'],
        		'source'=>$vo['source'],
        		'scale'=>$vo['scale'],
        		'status'=>$vo['status'],
        		'last_contact_time'=>$vo['last_contact_time'],
        		'next_contact_time'=>$vo['next_contact_time'],
        		'it_scale'=>$vo['it_scale'],
        		'proposal'=>$vo['proposal'],
        		'team_id'=>$vo['team_id'],
        		'input_type'=>$vo['input'],
        		'is_valid'=>$vo['is_valid'],
        		'contact_num'=>$vo['contact_num'],
        		'consumption_amount'=>$vo['consumption_amount'] > 0 ? $vo['consumption_amount'] : null,
        		'account_type'=>$vo['account_type'] == 3 ? 2 : $vo['account_type'],
        		'is_gh'=>$vo['is_gh'],
        		'group'=>$vo['account_type'] == 3 ? 'baidu' : null,
        	];
        	if (!empty($vo['company'])) {
        		$tmp['name'] = $vo['company'].' '.$tmp['name'];
        	}
        	$save_datas[] = $tmp;
        }

        $chunk_result = array_chunk($save_datas, 1000);
        foreach ($chunk_result as $k => $new_list) {
        	$result = Db::name('customer')->insertAll($new_list);
        	dump($result);
        }

        
    }

    public function qy_hjzx()
    {
    	$dsn_config = [
	        'type'=>'mysql',
	        'hostname'=> '127.0.0.1',
	        'database'=> 'delisystemdb',
	        'username'=> 'root',
	        'password'=> 'root',
	    ];
        $list = Db::connect($dsn_config)->table('cms_hjzx_record')->select();
        $save_datas = [];
        foreach ($list as $k => $vo) {
        	$save_datas[] = [
        		'id'=>$vo['id'],
        		'customer_id'=>$vo['customer_id'],
        		'sale_id'=>$vo['sale_id'],
        		'ctime'=>$vo['ctime'],
        		'caller'=>$vo['caller'],
        		'callee'=>$vo['callee'],
        		'call_date'=>$vo['call_date'],
        		'call_type'=>$vo['call_type'],
        		'answer_date'=>$vo['answer_date'],
        		'hangup_date'=>$vo['hangup_date'],
        		'hangup_cause'=>$vo['hangup_cause'],
        		'bill'=>$vo['bill'],
        		'duration'=>$vo['duration'],
        		'record_file'=>$vo['record_file'],
        		'status'=>$vo['bill'] > 0 ? 1 : 0,
        		'is_top'=>$vo['is_top']
        	];
        }

        $chunk_result = array_chunk($save_datas, 1000);
        foreach ($chunk_result as $k => $new_list) {
        	$result = Db::name('hjzx_record')->insertAll($new_list);
        	dump($result);
        }
        
    }

    public function qy_contact()
    {
    	$dsn_config = [
	        'type'=>'mysql',
	        'hostname'=> '127.0.0.1',
	        'database'=> 'delisystemdb',
	        'username'=> 'root',
	        'password'=> 'root',
	    ];
        $list = Db::connect($dsn_config)->table('cms_contact')->select();
        $save_datas = [];
        foreach ($list as $k => $vo) {
        	$save_datas[] = [
        		'id'=>$vo['id'],
        		'customer_id'=>$vo['customer_id'],
        		'contact_time'=>$vo['contact_time'],
        		'content'=>$vo['content'],
        		'sale_id'=>$vo['sale_id'],
        		'mode'=>$vo['mode'],
        		'status'=>$vo['customer_status'],
        		'hjzx_record_id'=>$vo['hjzx_record_id'],
        		'ctime'=>$vo['ctime'],
        	];
        }

     
        $chunk_result = array_chunk($save_datas, 1000);
        foreach ($chunk_result as $k => $new_list) {
            $result = Db::name('contact')->insertAll($new_list);
            dump($result);
        }
    }


   
}
